package com.blue.web;

import com.blue.exceptions.MoneyNotEnoughException;
import com.blue.exceptions.TransferException;
import com.blue.service.AccountService;
import com.blue.service.impl.AccountServiceImpl;
import com.blue.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {
    private AccountService service = new AccountServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取账单数据
        String fromActno = request.getParameter("fromActno");
        String toActno = request.getParameter("toActno");
        Double money = Double.parseDouble(request.getParameter("money"));

        // 调用 Service 的转账方法完成转账
        try {
            service.transfer(fromActno, toActno, money);
            // 调用 View 展示结果
            response.sendRedirect("/demo-04/success.html");

        } catch (TransferException e) {
            e.printStackTrace();
            // 调用 View 展示结果
            response.sendRedirect("/demo-04/error2.html");

        } catch (MoneyNotEnoughException e) {
            e.printStackTrace();
            // 调用 View 展示结果
            response.sendRedirect("/demo-04/error1.html");
        }
    }
}
